package com.winit.project.handler.impl;

import com.winit.core.server.linux.LinuxLocalServer;
import com.winit.project.core.edition.PackageEdition;
import com.winit.project.core.edition.PackageEditionConfig;
import com.winit.project.handler.BuildHandler;
import com.winit.project.util.ProjectMessageUtil;
import com.winit.project.util.ProjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 处理构建过程中,每个命令输出的日志
 * 需要输出到ws队列.并保存到本地文件
 * Created by wangjian on 16/9/13.
 */
public class BuildHandlerImpl extends BuildHandler {

    private static final Logger logger = LoggerFactory.getLogger(BuildHandlerImpl.class);

    private List<String> logFilePathList = new ArrayList<>();

    @Override
    public void addLogFile(String filePath) {
        if (this.logFilePathList.contains(filePath)) {
            return;
        }
        this.logFilePathList.add(filePath);
    }

    @Override
    public void removeLogFile(String filePath) {
        if (!this.logFilePathList.contains(filePath)) {
            return;
        }
        this.logFilePathList.remove(filePath);
    }

    @Override
    public void onMessage(String msg) {
        if (StringUtils.isEmpty(msg.trim())) {
            return;
        }

        Pattern pattern = Pattern.compile("^[0-9]*/[0-9]* KB.*");
        Matcher matcher = pattern.matcher(msg);
        boolean flag = matcher.matches();
        if (flag) {
            return;
        }
        logger.info("BuildHandlerImpl:" + msg);
        this.sendMessageToMQ(msg);
        this.saveMsgToFile(msg);
    }

    /**
     * 向队列发送消息
     *
     * @param msg
     */
    private void sendMessageToMQ(String msg) {
        ProjectMessageUtil.projectBuildLogMes(this.projectName, msg);
    }

    @Override
    public void saveMsgToFile(String msg) {
        if (this.logFilePathList.size() == 0) {
            return;
        }
        LinuxLocalServer localServer = null;
        try {
            localServer = LinuxLocalServer.getInstance();
            for (String path : this.logFilePathList) {
                localServer.writeLogFile(msg, path, true);
            }
        } catch (Exception e) {
            logger.error("执行构建,输出日志到文件异常.", e);
        }
    }

    @Override
    public void onSvnVersion(String svnUrl, String workDir, long version) {
        //发送消息
        this.onMessage("执行构建,更新svn代码.svn地址:" + svnUrl + ",代码路径:" + workDir + ",当前svn版本号:" + version);
    }
}
